<template>
	<view class="page">
		<view class="top">
			<text class="title">硬件配网</text>
			<text class="sub-title">请连接硬件WiFi后，进行操作</text>
		</view>
		<view class="form-wrapper">
			<up-form labelPosition="left" :model="form" :rules="rules" ref="formRef" labelWidth="60px">
				<up-form-item label="设备号" borderBottom>
					<up-input v-model="form.device_id" border="none" clearable></up-input>
					<template #right>
						<button @click="openScan" style="margin-left: 10px;" size="mini">扫一扫</button>
					</template>
				</up-form-item>
				<up-form-item label="商家" prop="shop_id" borderBottom>
					<!-- <up-input v-model="form.shop_id" border="none" clearable></up-input> -->
					<text>{{ form.shop_name }}</text>
					<template #right>
						<button :disabled="shopList.length === 0" @click="shopPickerShow = true"
							style="margin-left: 10px;" size="mini">选择</button>
					</template>
				</up-form-item>
				<up-form-item label="WiFi" prop="wifi" borderBottom>
					<up-input v-model="form.wifi" border="none" clearable></up-input>
					<template #right>
						<button @click="routerToWifi" style="margin-left: 10px;" size="mini">选择</button>
					</template>
				</up-form-item>
				<up-form-item label="密码" prop="password" borderBottom>
					<up-input v-model="form.password" border="none" clearable></up-input>
				</up-form-item>
			</up-form>
		</view>
		<BindMobile @onbind="getShopList"></BindMobile>
		<view v-if="hasMobile" style="width: 60%;margin: 0 auto;">
			<button :disabled="!form.wifi || !form.password" type="primary" @click="handleSend">配置网络</button>
		</view>

		<up-picker v-if="shopList.length" :show="shopPickerShow" :columns="shopList" keyName="label"
			@cancel="shopPickerShow = false" @confirm="shopConfirm"></up-picker>
	</view>
</template>

<script setup>
	// Wi-Fi名：ESP8266 密码：123456789   ip:192.168.4.1  端口：5050
	import api from '@/api/app.js'
	import useAppStore from '@/store/app.js'
	import {
		getQueryString,
	} from '@/common/utils/index.js'
	import {
		connectingDevice
	} from '@/common/js/device.js'

	const appStore = useAppStore()
	const hasMobile = computed(() => {
		return appStore.hasMobile
	})
	const shopList = ref([])
	const formRef = ref(null);
	// const deviceId = ref('')
	const shopPickerShow = ref(false)
	const form = ref({
		device_id: '',
		shop_id: '',
		shop_name: '',
		wifi: 'test',
		password: '123456789',
	})


	const res = ref('')

	const rules = {
		device_id: {
			type: 'number',
			required: true,
			message: '请录入设备号',
			trigger: ['blur', 'change']
		},
		shop_id: {
			type: 'number',
			required: true,
			message: '请选择商家',
			trigger: ['blur', 'change']
		},
		wifi: {
			type: 'string',
			required: true,
			message: '请选择WiFi',
			trigger: ['blur', 'change']
		},
		password: {
			type: 'string',
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change']
		}
	}


	function handleSend() {
		formRef.value.validate().then(valid => {
			if (valid) {
				// 绑定设备
				api.bindDevice({
					shop_id: form.value.shop_id,
					device_id: form.value.device_id
				}).then(res => {
					console.log('bind result：', res)
				})
				// 硬件加密通讯
				// connectingDevice(form.value.device_id.value, form.value.wifi, form.value.password).then(res => {
				// 	console.log(res)
				// }).catch((err) => {
				// 	uni.showToast({
				// 		icon: 'fail',
				// 		title: err.message || '连接失败', // 使用 err.message 以确保错误信息的可读性
				// 		duration: 2000 // 设置显示时间，可根据需要调整
				// 	});
				// })
				uni.$u.toast('校验通过')
			} else {
				uni.$u.toast('校验失败')
			}
		}).catch(() => {
			// 处理验证错误  
		});
	}

	const eventBusName = 'bindexWifiSelected'

	function routerToWifi() {
		uni.$once(eventBusName, function(wifi) {
			console.log('返回的WiFi信息：', wifi)
			form.value.wifi = wifi.SSID
		})
		uni.navigateTo({
			url: `/pages/wifi/wifi?eventBusName=${eventBusName}`
		})
	}

	function openScan() {
		uni.scanCode({
			scanType: ['qrCode'],
			success(res) {
				const url = res.result
				if (!url.includes('koc365')) {
					uni.$u.toast('请扫描元族设备二维码')
				} else if (!url.includes('deviceId')) {
					uni.$u.toast('获取设备号失败')
				} else {
					const deviceId = getQueryString(url, 'deviceId')
					form.value.device_id = deviceId
					uni.$u.toast(`获取成功：${deviceId}`)
				}
				// console.log('条码内容：' + res.result);
			}
		})
	}

	function shopConfirm(e) {
		if (e.value && e.value[0]) {
			const target = e.value[0]
			form.value.shop_id = target.id
			form.value.shop_name = target.label
		}
		shopPickerShow.value = false
	}

	function getShopList() {
		return api.getShopList({}).then(res => {
			const list = res.data.data.map(item => {
				return {
					label: item.nickname,
					id: item.shop_id,
				}
			})
			shopList.value = [list];
		})
	}

	// 绑定手机号
	// function onGetPhoneNumber(e) {
	// 	appStore.bindMobile(e).then(()=> {
	// 		getShopList()
	// 	})
	// }

	onUnload(() => {
		uni.$off(eventBusName)
	})

	onLoad(async (query) => {
		if (query.deviceId) {
			form.value.device_id = query.deviceId
		} else if (query.q && query.q.includes('deviceId')) {
			form.value.device_id = getQueryString(query.q, 'deviceId')
		} else {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '获取设备id失败',
			// 	duration: 3000,
			// })
		}
		if (!appStore.isLogin) {
			appStore.login().then(res => {
				if (hasMobile.value && form.value.device_id) {
					getShopList()
				}
			})
		} else {
			if (hasMobile.value && form.value.device_id) {
				getShopList()
			}
		}
	})
</script>

<style lang="scss" scoped>
	.page {
		padding: 0 16px;
	}

	.top {
		padding: 32px 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.title {
		font-size: 22px;
		font-weight: 500;
		margin-bottom: 16px;
	}

	.sub-title {
		font-size: 17px;
	}

	.form-wrapper {
		margin-bottom: 32px;
		min-height: 50vh;
	}
</style>